import axios, { type AxiosResponse } from "axios";
import cookie from "js-cookie";
import router from "@/router"
import qs from "qs"
import { ElMessage } from "element-plus";
import { useUserInfoStore } from '@/stores/userInfo'

/**
 * 声明接口TypeResponse扩展属性
 */
declare interface TypeResponse extends AxiosResponse {
  /**错误消息 */
  errmsg: string;
  /**错误码 10006令牌过期 ，200正常*/
  errno: number;
  url: string
}

let baseURL = ""
let host = ""
if (process.env.NODE_ENV === "development") {
  baseURL = "/m.api"
  host = ""
} else {
  baseURL = "http://zxwyit.cn:8080/m.api"
  host = "http://zxwyit.cn:8080"
}
const instance = axios.create({
  baseURL,
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
//请求拦截，设置请求头
instance.interceptors.request.use(
  (config) => {
    if (config.headers) {
      config.headers!.AdminToken = cookie.get('adminToken');
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截，数据处理
// 需要无痛刷新的操作页面
const METHOD_TYPE = ["_mt=edit","_mt=update", "_mt=create", "_mt=delete","_mt=options"]
instance.interceptors.response.use(
  async (res: AxiosResponse) => {
    let data = res.data
    let { errno, errmsg } = data
    let path = router.currentRoute.value.fullPath
    if (10006 === errno) {
      let index = METHOD_TYPE.findIndex(item => res.config.data.includes(item))
      if (-1 == index) {
        console.log(res.config.data)
        router.replace({ path: '/login', query: { back: path } })
        return
      } else {
        const store = useUserInfoStore()
        let { errmsg,errno, data } = await post({ _gp: 'admin', _mt: 'login', ...store.loginInfo })
        if (200 === errno) {
          cookie.set('adminToken', data)
        } else {
          router.replace({ path: "/login", query: { back: path } })//登入后需要跳回的地址
          console.log(errmsg,errno)
          return Promise.reject({ errno, errmsg,data})
        }
        return instance.request(res.config)
      }
    }
    return data;
  },
  (error) => {
    return Promise.reject(error);
  }
);
/**
 * get请求
 * @param params 请求参数，默认为空对象
 * @returns 返回类型Promise<TypeResponse>
 */
const get = (params: object = {}): Promise<TypeResponse> => instance.get("", { params });
/**
 * post请求
 * @param data 请求data数据，必填
 * @param params 请求params数据，默认为空
 * @returns 返回类型Promise<TypeResponse>
 */
const post = (data: object, params: object = {}): Promise<TypeResponse> =>
  instance.post("", qs.stringify(data), { params });

function upload(data: FormData): Promise<TypeResponse> {
  return instance.post("../upload/admin", data)
}
//暴露方法
export { get, post, host, upload };
